//
//  HD_LY_NetHelper.m
//  HDNetworkManagerDemo
//
//  Created by liuyi on 2017/5/15.
//  Copyright © 2017年 liuyi. All rights reserved.
//

#import "HD_LY_NetHelper.h"
#import "HD_LY_Cache.h"
#import "LCCoolHUD.h"
#import "AFNetworkActivityIndicatorManager.h"

//屏幕尺寸
#define ScreenWidth    [UIScreen mainScreen].bounds.size.width
#define ScreenHeight   [UIScreen mainScreen].bounds.size.height


@interface LoadingView : UIView

- (void)dissmissView;

@end

@implementation LoadingView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        //设置普通状态的动画图片
        /*
        NSMutableArray *idleImages = [NSMutableArray array];
        for (NSUInteger i = 0; i<=16; i++)
        {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"LivePhotoOn_3_5_%zd", i]];
            [idleImages addObject:image];
        }
        UIImageView *imaegCustomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        imaegCustomView.center = self.center;
        [self addSubview:imaegCustomView];
        imaegCustomView.animationImages = idleImages;
        [imaegCustomView setAnimationRepeatCount:0];
        [imaegCustomView setAnimationDuration:(idleImages.count + 1) * 0.075];
        [imaegCustomView startAnimating];
        self.backgroundColor = [UIColor whiteColor];
         */
        
         //可以自定义添加想要显示的加载动画
        [LCCoolHUD showLoading:[HDDeclare UIString:@"loading"]];//加载HUD1
//      [LCCoolHUD showLoadingWithJGHUD:@"正在加载中..." inView:self zoom:YES shadow:NO];//加载HUD2
    }
    return self;
}

- (void)dissmissView
{
    [LCCoolHUD hideInKeyWindow];
    for (UIView *subiew in self.subviews) {
        [subiew removeFromSuperview];
    }
    [self removeFromSuperview];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self slideOutFromCenter];
//    });
}

- (void)slideOutFromCenter
{
    [LCCoolHUD hideInKeyWindow];
    /*
    [UIView animateWithDuration:0.1f animations:^{
        self.transform =
        CGAffineTransformConcat(CGAffineTransformIdentity,
                                CGAffineTransformMakeScale(3.0f, 3.0f));
        self.alpha = 0.0f;
    } completion:^(BOOL completed)
    {
        [self fadeOut];
//        [LCCoolHUD hideWithJGHUD];
    }];
     */
}

- (void)fadeOut {
    [UIView animateWithDuration:0.1f animations:^{
        self.alpha = 0.0f;
    } completion:^(BOOL completed) {
        for (UIView *subiew in self.subviews) {
            [subiew removeFromSuperview];
        }
        [self removeFromSuperview];
    }];
}

@end

@interface HD_LY_NetHelper ()

@end

@implementation HD_LY_NetHelper

+ (void)requestWithType:(httpMethod)httpMethod
                withUrl:(NSString *)url
             withParams:(NSDictionary *)params
               toShowVC:(UIViewController *)showVC
                success:(ResponseSuccess)success
                   fail:(ResponseFail)fail
                showHUD:(BOOL)show
                isCache:(BOOL)cache
{
    if (!url) return;
    NSString *urlStr = url;
    if (httpMethod == GET)
    {
        [self getWithType:httpMethod withUrl:urlStr withParams:params toShowVC:showVC success:success fail:fail showHUD:show isCache:cache];
    }else
    {
        [self postWithType:httpMethod withUrl:urlStr withParams:params toShowVC:showVC success:success fail:fail showHUD:show isCache:cache];
    }
}

//GET 请求
+ (void)getWithType:(httpMethod)httpMethod
            withUrl:(NSString *)url
         withParams:(NSDictionary *)params
           toShowVC:(UIViewController *)showVC
            success:(ResponseSuccess)success
               fail:(ResponseFail)fail
            showHUD:(BOOL)show
            isCache:(BOOL)cache

{
    LoadingView *loadingView = nil;
    if (show) {
        loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [showVC.navigationController.view addSubview:loadingView];
    }
    AFHTTPSessionManager *manager = [self getAFManager];
    if (cache)//需要缓存功能
    {
        if (![HD_LY_NetHelper requestBeforeJudgeConnect]) {
            NSLog(@"\n\n----%@------\n\n",@"没有网络");
            NSDictionary *dicData = (NSDictionary *)[HD_LY_Cache readDataCache:url parameters:params];
            if (success) { success(dicData);}//返回缓存数据
            if (show) {[loadingView dissmissView];}
            return;
        }
        [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {success(responseObject);}
            if (show) {[loadingView dissmissView];}
            NSDictionary *dic = responseObject;
            [HD_LY_Cache saveDataCache:dic forKey:url parameters:params];//更新缓存数据
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (fail) {fail(error);}
            if (show) {[loadingView dissmissView];}
            [LCCoolHUD showFailureOblong:@"网络请求失败" zoom:NO shadow:NO];
        }];
    }else {
        [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {success(responseObject);}
            if (show) {[loadingView dissmissView];}
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (fail) {fail(error);}
            if (show) {[loadingView dissmissView];}
            [LCCoolHUD showFailureOblong:@"网络请求失败" zoom:NO shadow:NO];
        }];
    }
}

//POST 请求
+ (void)postWithType:(httpMethod)httpMethod
             withUrl:(NSString *)url
          withParams:(NSDictionary *)params
            toShowVC:(UIViewController *)showVC
             success:(ResponseSuccess)success
                fail:(ResponseFail)fail
             showHUD:(BOOL)show
             isCache:(BOOL)cache

{
    LoadingView *loadingView = nil;
    if (show) {
        loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [showVC.navigationController.view addSubview:loadingView];
    }
    AFHTTPSessionManager *manager = [self getAFManager];
    if (cache) {
        if (![HD_LY_NetHelper requestBeforeJudgeConnect]) {
            NSDictionary *dicData = (NSDictionary *)[HD_LY_Cache readDataCache:url parameters:params];
            if (success) { success(dicData);}
            if (show) {[loadingView dissmissView];}
            return;
        }
        [manager POST:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {success(responseObject);}
            if (show) {[loadingView dissmissView];}
            NSDictionary *dic = responseObject;
            [HD_LY_Cache saveDataCache:dic forKey:url parameters:params];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (fail) {fail(error);}
            if (show) {[loadingView dissmissView];}
            [LCCoolHUD showFailureOblong:@"网络请求失败" zoom:NO shadow:NO];
        }];
    }else {
        [manager POST:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {success(responseObject);}
            if (show) {[loadingView dissmissView];}
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (fail) {fail(error);}
            if (show) {[loadingView dissmissView];}
            [LCCoolHUD showFailureOblong:@"网络请求失败" zoom:NO shadow:NO];
        }];
    }
}

//初始化设置
+ (AFHTTPSessionManager *)getAFManager {
    static AFHTTPSessionManager *httpManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        httpManager = [AFHTTPSessionManager manager];
        httpManager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
        httpManager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
        //httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置返回NSData 数据
        httpManager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
        httpManager.requestSerializer.timeoutInterval= 15;//请求超时时间
        httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                                      @"text/html",
                                                                                      @"text/json",
                                                                                      @"text/plain",
                                                                                      @"text/javascript",
                                                                                      @"text/xml",
                                                                                      @"image/*"]];
    });
    return httpManager;
}

#pragma mark  ----网络判断-----
+ (BOOL)requestBeforeJudgeConnect
{
    struct sockaddr zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sa_len = sizeof(zeroAddress);
    zeroAddress.sa_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags =
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        printf("Error. Count not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        //[UIApplication sharedApplication].networkActivityIndicatorVisible =isNetworkEnable;/*  网络指示器的状态： 有网络 ： 开  没有网络： 关  */
    });
    return isNetworkEnable;
}

#pragma mark ----- 上传图片 ------
+ (void)uploadImgwithUrl:(NSString *)url
              withParams:(NSDictionary *)params
                toShowVC:(UIViewController *)showVC
                 keyName:(NSString *)name
                 imgData:(UIImage *)img
                 success:(ResponseSuccess)success
                    fail:(ResponseFail)fail
{
    if (!url) return;
    NSString *urlStr = url;
    LoadingView *loadingView = nil;
    if (showVC) {
        loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [showVC.navigationController.view addSubview:loadingView];
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 5.0f;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    //
    [session POST:urlStr parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传文件
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str      = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        NSData *imageData  = UIImageJPEGRepresentation(img, 1.0);
        [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
    
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (showVC) {[loadingView dissmissView];}
        if (success) {success(responseObject);}
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {fail(error);}
        if (showVC) {[loadingView dissmissView];}
        [LCCoolHUD showFailureOblong:@"网络请求失败" zoom:NO shadow:NO];
    }];
}




@end





























